package com.bmslz.monitor.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bmslz.monitor.base.factory.RuleDataCompareFactory;
import com.bmslz.monitor.base.util.StringUtils;
import com.bmslz.monitor.base.entity.AlarmModelRule;
import com.bmslz.monitor.mapper.AlarmModelRuleMapper;
import com.bmslz.monitor.service.IAlarmModelRuleService;
import com.bmslz.monitor.service.RuleDataCompare;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 告警规则
 * @Author: bobo
 * @Date: 2025-08-10
 * @Version: V1.0
 */
@Service
public class AlarmModelRuleServiceImpl extends ServiceImpl<AlarmModelRuleMapper, AlarmModelRule> implements IAlarmModelRuleService {

    @Autowired
    private RuleDataCompareFactory ruleDataCompareFactory;

    @Override
    public List<AlarmModelRule> matchRule(String alarmModelId, String projectNo, String attKey, String attValue) {
        //查找这个项目下这个测点的所有规则 一个测点最多拥有 1 紧急 2 告警 3 预警 三条规则
        List<AlarmModelRule> res = new ArrayList<>();
        List<AlarmModelRule> alarmModelRules = baseMapper.selectList(new LambdaQueryWrapper<AlarmModelRule>().eq(AlarmModelRule::getAlarmModelId, alarmModelId).eq(AlarmModelRule::getAttKey, attKey));
        for (AlarmModelRule alarmModelRule : alarmModelRules) {
            String condition = alarmModelRule.getConditionTag();
            String dataValue = alarmModelRule.getDataValue();
            String attKeyType = alarmModelRule.getAttKeyType();
            RuleDataCompare compare = ruleDataCompareFactory.getStrategy(attKeyType);
            if (compare.compare(condition, dataValue, attValue)) {
                //匹配规则成功
                res.add(alarmModelRule);
            }
        }
        return res;
    }

    @Override
    public List<AlarmModelRule> getByModelId(String modelId) {
        if(StringUtils.isEmpty(modelId)){
            return new ArrayList<>();
        }
        return baseMapper.selectList(new LambdaQueryWrapper<AlarmModelRule>().eq(AlarmModelRule::getAlarmModelId,modelId));
    }

    @Override
    public List<AlarmModelRule> queryRuleByKey(String alarmModelId, String attKey) {
        if(StringUtils.isEmpty(alarmModelId) || StringUtils.isEmpty(attKey) ){
            return new ArrayList<>();
        }

        return baseMapper.selectList(new LambdaQueryWrapper<AlarmModelRule>().eq(AlarmModelRule::getAlarmModelId,alarmModelId).eq(AlarmModelRule::getAttKey,attKey));
    }
}
